package com.cn.medicalcare.controller.filter;

import com.cn.medicalcare.controller.backstageservlet.login.LoginServlet;
import com.cn.medicalcare.customtool.JedisUtil;
import com.cn.medicalcare.customtool.JsonTool;
import com.cn.medicalcare.pojo.Admin;
import com.cn.medicalcare.service.serviceimpl.LoginServiceImpl;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

@WebFilter(filterName = "backstagefilter", urlPatterns = "/backstage/*")
public class Filter003_BackStage implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String token = request.getParameter("sessionId");
        Admin admin = null;
        Map<String, Object> map = new LinkedHashMap<>();
        if (StringUtils.isNotEmpty(token)) {
            admin = JsonTool.toObject(JedisUtil.jedisDo(j -> {
                j.select(15);
                String adminjson = j.get(token);
                if (StringUtils.isNotEmpty(adminjson))
                    j.expire(token, LoginServiceImpl.TOKEN_TIME);
                return adminjson;
            }), Admin.class);
        }
        if (admin == null) {
            map.put("status", 403);
            map.put("message", "权限不足");
            response.getWriter().print(JsonTool.toJson(map));
        } else {
            filterChain.doFilter(request, response);
        }

    }

    @Override
    public void destroy() {

    }
}
